package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class LISTHandle implements Handle {
	FtpSession ftpSession;
	static SimpleDateFormat sdf = new SimpleDateFormat("MMM dd HH:mm", Locale.ENGLISH);

	public LISTHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		String path = PathConvert.toServerPath(ftpSession.currentDir, "");
		File file = new File(path);
		File[] files = file.listFiles();
		for (File f : files) {
			String template = "#{dir}rwxr--r--   1 user     group        #{size} #{date} #{fileName}\r\n";
			long time = f.lastModified();
			Date date = new Date(time);
			template = template.replace("#{date}", sdf.format(date));
			template = template.replace("#{fileName}", f.getName());
			if (f.isDirectory()) {
				template = template.replace("#{dir}", "d");
				template = template.replace("#{size}", "1024");
			} else {
				template = template.replace("#{dir}", "-");
				template = template.replace("#{size}", Long.toString(f.length()));
			}
			os.write(template.getBytes());
		}
		os.flush();
	}
}